package com.rou.im.boot.starter.server;

import com.rou.im.boot.starter.server.netty.EventLoopGroupManager;
import com.rou.im.boot.starter.server.netty.config.NettyConfigProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-01 17:50
 */
@Configuration(proxyBeanMethods = false)
public class IMServerInitializerConfiguration implements SmartLifecycle, Ordered {

    private static final Log log = LogFactory.getLog(IMServerInitializerConfiguration.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ServerBootstrap serverBootstrap;

    @Autowired
    private EventLoopGroupManager manager;

    @Autowired
    private NettyConfigProperties config;

    private boolean running;

    private int order = 1;

    @Override
    public void start() {
        ExecutorService executorService = Executors.newSingleThreadExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setName("IM-SERVER");
            thread.setDaemon(false);
            return thread;
        });
        executorService.execute(new IMServerStartTask());
    }


    private void publish(ApplicationEvent event) {
        this.applicationContext.publishEvent(event);
    }

    @Override
    public void stop() {
        this.running = false;
        // 关闭线程
        manager.close();

    }

    @Override
    public boolean isRunning() {
        return this.running;
    }

    @Override
    public int getPhase() {
        return 0;
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    private class IMServerStartTask implements Runnable {
        @Override
        public void run() {
            try {
                log.info("------------开始启动server，端口:" + config.getServer().getPort() + "-------");
                ChannelFuture future = serverBootstrap.bind().sync();
                if (future.isSuccess()) {
                    //发布server启动成功事件
                }
                IMServerInitializerConfiguration.this.running = true;
                future.channel().closeFuture().sync();
            } catch (Exception ex) {
                log.error("Could not initialize im server", ex);
                ex.printStackTrace();
            }
        }
    }

}
